<script  setup>
import {onMounted, ref} from "vue";
import {selectSale,addCustomer,updateCustomer,deleteCustomer} from "@/api/sale.js";
import { useRouter } from 'vue-router';
import {ElMessage, ElMessageBox} from 'element-plus'



// 获取路由实例
const router = useRouter();
//自定义的响应式数组
const tableData =ref([])
//页数
const size = ref('default')
const background = ref(false)
//当前页
const PageNum = ref(1)
//每页显示条数
const PageSize = ref(10)
//总条数
const total = ref(null)
//定义是否为编辑状态的响应式变量
const disabled = ref(false)
// 定义对话框是否显示的响应式变量
const Isdisable = ref(false)
//管理表单提交状态
const submitting = ref(false)








//输入框绑定的响应式变量
const customerId = ref("")//客户id
const customerName= ref("")//客户名称

//当每页条数发生了变化，调用此函数
const handleSizeChange = (size) => {
   PageSize.value = size
   PageNum.value=1
   select()
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  PageNum.value = num
  select()
}
//查询按钮
const select= async ()=>{
  try {
    const response= await selectSale(
        customerId.value,
        customerName.value,
        PageNum.value,
        PageSize.value
    )
    console.log(response)
    //分页条件数据模型
    tableData.value= response.data.data.rows
    for (const table of tableData.value) {
      table.cooperationStartDate=table.cooperationStartDate.replace('T', ' ');// 结果："2025-03-09 00:04:08"
      table.establishmentDate=table.establishmentDate.replace('T', ' ');// 结果："2025-03-09 00:04:08"
    }
    total.value = response.data.data.total
    size.value=response.data.data.pages
  }catch(error){
    console.error("请求出错",error)
  }
}






// 重置表单
const resetForm = () => {
  Customer.value={
    customerId:'',//客户编号
    customerName:'',//客户的全称
    customerType:'',//客户类型
    establishmentDate:'',//客户公司成立的年份
    registeredCapital:'',//客户注册时的资金数额
    contactPerson:'',//负责与公司对接的人员名
    contactPhone:'',//联系人的常用电话号码
    contactEmail:'',//用于业务沟通的电子邮箱地址
    cooperationStartDate:'', //与客户开始合作的日期
    cooperationStatus:'',//客户合作状态
    creditRating:'',//信用评估等级
    remarks:''//用于记录其他需要说明的信息
  }
  Isdisable.value=false
}

//定义一个客户对象
const Customer = ref({
  customerId:'',//客户编号
  customerName:'',//客户的全称
  customerType:'',//客户类型
  establishmentDate:'',//客户公司成立的年份
  registeredCapital:'',//客户注册时的资金数额
  contactPerson:'',//负责与公司对接的人员名
  contactPhone:'',//联系人的常用电话号码
  contactEmail:'',//用于业务沟通的电子邮箱地址
  cooperationStartDate:'', //与客户开始合作的日期
  cooperationStatus:'',//客户合作状态
  creditRating:'',//信用评估等级
  remarks:''//用于记录其他需要说明的信息
})

//点击跳转添加按钮
const goToAdd=()=>{
  //false表示可以添加
  disabled.value=false
  resetForm()
  Isdisable.value=true
}

//创建对象，存取修改所用的对象内容(修改表单)
const updateI=(row)=>{
  console.log(row)
  Isdisable.value=true
  //true表示可以修改
  disabled.value=true
  Customer.value.customerId=row.customerId
  Customer.value.customerName=row.customerName
  Customer.value.customerType=row.customerType
  Customer.value.establishmentDate=row.establishmentDate
  Customer.value.registeredCapital=row.registeredCapital
  Customer.value.contactPerson=row.contactPerson
  Customer.value.contactPhone=row.contactPhone
  Customer.value.contactEmail=row.contactEmail
  Customer.value.cooperationStartDate=row.cooperationStartDate
  Customer.value.cooperationStatus=row.cooperationStatus
  Customer.value.creditRating=row.creditRating
  Customer.value.remark=row.remark
}


//删除表单
const del = (row) => {
  ElMessageBox.confirm(
      '确定要删除数据吗？',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async ()=>{
        const rows=await deleteCustomer(row.customerId)
        ElMessage(rows.data.msg)
        await select();
      }
  )
}


onMounted(()=>{
  select()
})


//修改添加函数
const submitForm = async () => {
  // 提取日期格式化函数
  const formatDate = (dateStr) => {
    const date = new Date(dateStr);
    const iso = date.toISOString();
    return iso.split('T')[0] + 'T' + iso.split('T')[1].split('.')[0];
  };
  // 格式化日期,重新赋值回原对象
  Customer.value.cooperationStartDate = formatDate(Customer.value.cooperationStartDate);
  Customer.value.establishmentDate = formatDate(Customer.value.establishmentDate);
  // console.log(Customer.value)
  if (!disabled.value){
    const add = await addCustomer(Customer.value)
    // console.log(add)
    ElMessage.success(add.data.msg)
    await select()
  } else{
    const update = await updateCustomer(Customer.value)
    // console.log(update)
    ElMessage.success(update.data.msg)
    await select()
  }
  Isdisable.value=false
}


//定义验证规则
const rules = {
  customerName: [
    { required: true, message: '请输入供应商名称', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  customerType: [
    {
      required: true,
      message: '请选择客户类型',
      trigger: 'change',
    },
  ],
  establishmentDate: [

    { required: true, message: '客户成立日期', trigger: 'blur' },

  ],
  registeredCapital: [
    { required: true, message: '注册资本', trigger: 'blur' },
    { pattern: /^(\d+(\.\d{2})?)$/, message: '注册资产必须为数字,并且必须为小数点后两位', trigger: 'blur' }
  ],
  contactPerson: [
    { required: true, message: '请输入客户联系人姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入客户联系人电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
    { min: 11, max: 11, message: '长度应为11个字符', trigger: 'blur' }
  ],
  contactEmail: [
    { required: true, message: '请输入客户电子邮箱地址', trigger: 'blur' },
    { pattern: /^[\w]+@\w+\.\w{2,}$/, message: '请输入正确的客户电子邮箱', trigger: 'blur' },
    { min: 2, max: 64, message: '长度在 2 到 64 个字符', trigger: 'blur' }
  ],
  cooperationStartDate: [
    { required: true, message: '请输入合作开始日期', trigger: 'blur' },
  ],
  creditRating: [
    { required: true, message: '请输入信用评估等级', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],

}
//作用是生成一个包含两个选项的数组
const options = Array.from({ length: 2 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}))


</script>

<template>

  <el-card>
    <el-row :gutter="20">
      <el-col :span="8" class="sou">
        <el-input
            type="text"
            placeholder="请输入客户id"
            v-model="customerId"
            suffix-icon="Search"
        />
      </el-col>
      <el-col :span="8" class="sou">
        <el-input
            type="text"
            placeholder="请输入客户名称"
            v-model="customerName"
            suffix-icon="Search"
        />
      </el-col>
      <el-button type="primary" @click="select()">搜索</el-button>

      <el-button type="primary" @click="goToAdd()">添加客户</el-button>

    </el-row>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column fixed prop="customerId" label="客户的全称" width="120" />
      <el-table-column fixed prop="customerName" label="客户的全称" width="120" />
      <el-table-column prop="customerType" label="客户类型" width="100" />
      <el-table-column prop="establishmentDate" label="客户公司成立的年份" width="200" />
      <el-table-column prop="registeredCapital" label="客户注册时的资金数额" width="120" />
      <el-table-column prop="contactPerson" label="联系人" width="120" />
      <el-table-column prop="contactEmail" label="电子邮箱地址" width="220" />
      <el-table-column prop="cooperationStartDate" label="开始合作的日期" width="200" />
      <el-table-column prop=" cooperationStatus" label="合作状态" width="120" />
      <el-table-column prop="creditRating" label="信用评级" width="100" />
      <el-table-column prop="remarks" label="备注信息" width="200" />


      <el-table-column fixed="right" label="操作" min-width="200">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="del(scope.row)">
            删除
          </el-button>
          <el-button link type="primary" size="small" @click="updateI(scope.row)">
            修改
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="demo-pagination-block">
      <!--分页查询-->
      <el-pagination
          v-model:current-page="PageNum"
          v-model:page-size="PageSize"
          :page-sizes="[5,10, 15]"
          :size="size"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="onCurrentChange"
      />
    </div>
  </el-card>


<!--  添加和修改的对话框-->

  <el-dialog  v-model="Isdisable" :title="disabled ? '编辑客户' : '新增客户'" width="30%" align-center>
    <el-form :model="Customer" :rules="rules"  ref="formRef" label-width="auto">


      <el-form-item label="客户id" prop="customerId" v-if="disabled">
        <el-input disabled v-model="Customer.customerId" placeholder="客户id"></el-input>
      </el-form-item>

      <el-form-item label="客户名称" prop="customerName">
        <el-input v-model="Customer.customerName" placeholder="客户名称"></el-input>
      </el-form-item>


      <el-form-item  label="客户类型" prop="customerType">
        <el-select-v2
            v-model="Customer.customerType"
            placeholder="客户类型"
            :options="options"
        />
      </el-form-item>

      <el-form-item label="客户公司成立日期" required>
        <el-col :span="11">
          <el-form-item prop="date1">
            <el-date-picker
                v-model="Customer.establishmentDate"
                type="date"
                aria-label="Pick a date"
                placeholder="Pick a date"
                style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col class="text-center" :span="2">
          <span class="text-gray-500">-</span>
        </el-col>
        <el-col :span="11">
          <el-form-item prop="date2">
            <el-time-picker
                v-model="Customer.establishmentDate"
                aria-label="Pick a time"
                placeholder="Pick a time"
                style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-form-item>

      <el-form-item label="注册资本" prop="registeredCapital">
        <el-input v-model="Customer.registeredCapital" placeholder="注册资本"></el-input>
      </el-form-item>

      <el-form-item label="客户联系人姓名" prop="contactPerson">
        <el-input v-model="Customer.contactPerson" placeholder="客户联系人姓名"></el-input>
      </el-form-item>

      <el-form-item label="联系电话" prop="contactPhone">
        <el-input v-model="Customer.contactPhone" placeholder="联系电话"></el-input>
      </el-form-item>

      <el-form-item label="联系邮箱" prop="contactEmail">
        <el-input v-model="Customer.contactEmail" placeholder="联系邮箱"></el-input>
      </el-form-item>


      <el-form-item label="合作开始日期" required>
        <el-col :span="11">
          <el-form-item prop="date1">
            <el-date-picker
                v-model="Customer.cooperationStartDate"
                type="date"
                aria-label="Pick a date"
                placeholder="Pick a date"
                style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col class="text-center" :span="2">
          <span class="text-gray-500">-</span>
        </el-col>
        <el-col :span="11">
          <el-form-item prop="date2">
            <el-time-picker
                v-model="Customer.cooperationStartDate"
                aria-label="Pick a time"
                placeholder="Pick a time"
                style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-form-item>


      <el-form-item label="合作状态" prop="cooperationstatus" v-if="disabled">
        <el-select v-model="Customer.cooperationStatus" placeholder="合作状态">
          <el-option label="正在合作" value="正在合作" />
          <el-option label="暂停合作" value="暂停合作" />
        </el-select>
      </el-form-item>

      <el-form-item label="信用评级" prop="creditRating">
        <el-select v-model="Customer.creditRating" placeholder="信用评级">
          <el-option label="A级" value="A级" />
          <el-option label="B级" value="B级" />
          <el-option label="C级" value="C级" />
        </el-select>
      </el-form-item>

      <el-form-item label="说明信息" prop="remarks">
        <el-input v-model="Customer.remarks" type="textarea" />
      </el-form-item>

    </el-form>

    <template  #footer>
      <el-button @click="resetForm">取消</el-button>
      <el-button type="primary" @click="submitForm"  :loading ="submitting">
        {{ submitting ? '提交中...' :disabled? '保存修改' : '添加' }}
      </el-button>
    </template>

  </el-dialog>




</template>



<style lang="scss">
*{
  padding: 0;
  margin: 0;
}

html,
body
{
  height: 100%;
}

.border-row {
  border: 1px solid #e4e7ed; /* 边框颜色和宽度 */
  padding: 10px; /* 可选：调整内边距 */
}

.border-col{
  height: 50px;
  border: 1px solid #e4e7ed; /* 边框颜色和宽度 */
  padding: 10px; /* 可选：调整内边距 */
}

.demo-pagination-block{
  height: 100px;
  margin-top: 10px;
  margin-bottom: 16px;
}

//.demo-pagination-block .demonstration {
//  margin-bottom: 16px;
//}

/* 输入框容器样式 */
.sou {
  margin-bottom: 15px; /* 输入框间距 */
}

/* 输入框样式 */
.el-input__inner {
  height: 40px; /* 输入框高度 */
  border-radius: 4px; /* 圆角 */
  font-size: 14px;
}

/* 搜索图标样式 */
.el-input__suffix-icon {
  color: #666; /* 图标颜色 */
  font-size: 16px;
}

/* 按钮样式（搜索按钮） */
.el-button--primary {
  margin-left: 25px;
  margin-right: 30px; /* 按钮间距 */
  padding: 0 20px; /* 内边距 */
}

/* 按钮样式（添加客户按钮） */
.el-button--primary:last-child {
  margin-left: 15px;
  margin-right: 0; /* 最后一个按钮去掉右侧间距 */
}



</style>